package cn.easyutil.veteran.web.provider;

import cn.easyutil.veteran.core.error.CommonException;
import cn.easyutil.veteran.core.error.ErrorEnum;
import cn.easyutil.veteran.web.advice.JsonRequestAdvice;
import cn.easyutil.veteran.web.session.SessionOperation;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.JavaType;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.reflect.Type;
import java.util.Set;

public class DefaultJsonRequestAdvice implements JsonRequestAdvice {

    @Override
    public String parseBody(String text, JavaType javaType,Type type, Class<?> controllerClass) {
        if(SessionOperation.toSecret.get()){
            //进行解密处理
            return decrypt(text);
        }
        return text;
    }

    @Override
    public Object beforeInvocation(Object body) {
        //手动参数校验
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<Object>> validate = validator.validate(body);
        if(validate!=null && validate.size()>0){
            for (ConstraintViolation<Object> violation : validate) {
                if(StringUtils.isNotBlank(violation.getMessage())){
                    throw new CommonException(violation.getMessage());
                }
            }
        }
        return body;
    }

    private String decrypt(String text) {
        String secret = SessionOperation.getUser().getSecret();
        try {
            AES aes = SecureUtil.aes(secret.getBytes());
            text = text.replace("\"","");
            return aes.decryptStr(text);
        }catch (Exception e) {
            throw new CommonException(ErrorEnum.aes_decrypt_error);
        }
    }
}
